#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cbm.h>
#include <conio.h>

#include "Buffers.h"
#include "Trim.h"
#include "Splitter.h"
#include "Drives.h"

#pragma code-name("CDCODE");
#pragma rodata-name("CDCODE");

unsigned char changeDirectory(unsigned char driveIndex)
{
	int r = 0, i = 0;
	int result = 0;
	drive_t *drive = &drives[driveIndex];
	tokenCollection_t *collection = NULL;
	parsedPath_t *path = NULL;
	static char buffer[256];
	char *text = NULL;

	if(0) cgetc();

	strcpy(buffer, buffer3);
	collection = splitString(buffer);
	text = collection->tokens[1].text;

	if(collection->count != 2)
	{
		printf("\nusage: cd path\n");
		free(collection);
		free(path);
		return 0;
	}

	path = parsePath(1, collection, driveIndex);

	driveIndex = getDrive(path->device);
	if(driveIndex == 0xFF) 
	{
		printf("\nUnknown device.");
		free(collection);
		free(path);
		return 1;
	}
	drive = &drives[driveIndex];

	if(drive->type == CBM15x1)
	{
		printf("\nDevice does not support directories.");
		free(collection);
		free(path);
		return 1;
	}

	//printf("\ntext: %s", text);

	if(strcmp(text, ".") == 0) 
	{
		free(collection);
		free(path);
		return 0;
	}
	
	if(text[0] == 0x5F || strcmp(text, "..") == 0)
	{
		sprintf(buffer3, "cd%c", 0x5F);
		strstr(path->path, text)[0] = 0;
		path->path[strlen(path->path)-1] = 0;
		strrchr(path->path, '/')[0] = 0;
		if(strlen(path->path) == 0)
		{
			strcpy(path->path, drive->type == VICE ? "/" : "//");
		}
	}
	else
	{
		if(drive->type == VICE)
		{
			sprintf(buffer3, "cd:%s", path->path);
		}
		else
		{
			sprintf(buffer3, "cd%s", path->path);
		}
	}
	printf("\n%s", buffer3);
	r = cbm_open(15, drive->device, 15, buffer3);
	result = cbm_read(15, buffer2, sizeof(buffer2));
	cbm_close(15);

	if(r == 0 && buffer2[0] == '0' && buffer2[1] == '0')
	{
		if(collection->tokens[1].text[0] != 0x5F && strcmp(collection->tokens[1].text, "..") != 0 && collection->tokens[1].text[0] != '/')
		{
			memset(drive->path, 0, sizeof(drive->path));
			strncpy(drive->path, path->path, sizeof(drive->path));
		}
		else if(collection->tokens[1].text[0] == 0x5F)
		{
			sprintf(drive->path, "/");
			if(drive->type != VICE)
			{
				strcat(drive->path, "/");
			}
		}
		else
		{
			memset(drive->path, 0, sizeof(drive->path));
			strncpy(drive->path, path->path, sizeof(drive->path));
		}
	}
	else
	{
		printf("\nERROR: %u - %s", r, buffer2);
	}

	free(collection);
	free(path);
	return r;
}
